# -*- coding: utf-8 -*-
import threading
import time
from Util.util import checkACC1Byte

class rxDetectionModuleThread(threading.Thread):
    def __init__(self, StateCtrl):
        super(rxDetectionModuleThread, self).__init__()
        self.Ctrl = StateCtrl
        self.__flag = threading.Event()  # 用于暂停线程的标识
        self.__flag.set()  # 设置为True
        self.__running = threading.Event()  # 用于停止线程的标识
        self.__running.set()  # 将running设置为True
        self.FrameHeader1 = [0x55]  # 帧头
        self.FrameHeader2 = [0xAA]  # 帧头
        self.FrameLength = 13  # 定帧帧长
        self.isAll = True
        pass

    def run(self):
        while self.Ctrl.Ser.isOpen() and self.__running.isSet():
            time.sleep(0.005)
            self.__flag.wait()
            if self.Ctrl.Ser.isOpen():
                if self.Ctrl.Ser.inWaiting():
                    frameHead1 = list(self.Ctrl.Ser.read(self.FrameHeader1.__len__()))
                    if frameHead1 == self.FrameHeader1:
                        frameHead2 = list(self.Ctrl.Ser.read(self.FrameHeader2.__len__()))
                        if frameHead2 == self.FrameHeader2:
                            FrameData = list(self.Ctrl.Ser.read(self.FrameLength - (self.FrameHeader1.__len__() + self.FrameHeader2.__len__())))
                            FrameData.insert(0, frameHead2[0])
                            FrameData.insert(0, frameHead1[0])
                            AccCheck = checkACC1Byte(FrameData[:(self.FrameLength - 1)])
                            if AccCheck == FrameData[self.FrameLength - 1]:  # 校验和正确
                                self.Ctrl.OnReceiveData(FrameData)
                            pass

    def pause(self):
        self.__flag.clear()  # 设置为False, 让线程阻塞

    def resume(self):
        self.__flag.set()  # 设置为True, 让线程停止阻塞

    def stop(self):
        self.__flag.set()  # 将线程从暂停状态恢复, 如何已经暂停的话
        self.__running.clear()  # 设置为False

    def setAll(self, isALL):
        self.isAll = isALL
        if self.isAll:
            self.FrameLength = 13  # 定帧帧长
        else:
            self.FrameLength = 7  # 定帧帧长